package com.zqm.experiment3.utils;


import com.zqm.experiment3.Pojo.COVID19Data;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;

import org.springframework.web.client.RestTemplate;

import org.springframework.web.util.UriComponentsBuilder;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.List;


public class HTTPUtil {


    public static Resource sendHttp(String url) {
        URI uri = UriComponentsBuilder.fromUriString(url).build(42);
        RequestEntity<Void> requestEntity = RequestEntity.get(uri)
                .header("User-Agent", "kkk")
                .build();
        ResponseEntity<Resource> response = new RestTemplate().exchange(requestEntity, Resource.class);
        return response.getBody();
    }

    public static void CSVParserAndRecord(Resource resource, List list) throws IOException {
        if (resource != null) {
            Reader reader = new InputStreamReader(resource.getInputStream(), "UTF-8");
            CSVParser parser = new CSVParser(reader, CSVFormat.EXCEL.withHeader());
            try {
                list.clear();
                for (CSVRecord record : parser) {
                    list.add(COVID19Data.builder()
                            .State(record.get("Province/State"))
                            .Region(record.get("Country/Region"))
                            .diffFromDay(Integer.parseInt(record.get(record.size() - 1)) - Integer.parseInt(record.get(record.size() - 2)))
                            .latestTotalCases(Integer.parseInt(record.get(record.size() - 1)))
                            .build());
                }
            } finally {
                reader.close();
            }
        }

    }

}
